/*
    Universe 跨服服务器  
*/

global.clone    = require('clone');
global.util     = require('util');
global.async   = require('async');
global.common   = require('./common.js');
global.Player   = require('./logic/player.js').Player;
global.Fighter  = require('./logic/fighter.js').Fighter;
global.Message  = require('./world/message.js').Message;
global.config   = require(require('fs').existsSync('../config.js') ? '../config.js' : './config.js');

var server  = require('./server.js');
global.logic   = require('./cloud/');
var logger  = require('./logger.js');
require('./global.js');

// 数据库, 缓存
global.gDBUser = null;
global.gDBMineUser = null;
global.gDBWorld = null;
global.gCache = null;

global.gCloudShop = null;
global.gBattleWorld = null;
global.gReplay = null;
global.gTroopMatch = null;
global.gActivity = null;
global.gServerMine = null;
global.gLuckyNumber = null;
global.gLottery = null;

logger.init({name:'cloud', debug:{backups:40}, error:{backups:8}});
(function main(){
    server.loadCache(function(cache){
        global.gCache = cache;
        INFO('redis connected');
    });

    server.loadConf();
    for (var mod in logic) {
        var initHandler = logic[mod]._initRuntime;
        if (initHandler) {
            initHandler();
        }
    }
    
    server.loadDB(function(db){
        global.gDBUser = db.collection('user');
        global.gDBWorld = db.collection('world');
        INFO('mongodb connected');

        // 加载用户
        global.gPlayers = require('./cloud/player.js').gPlayers;
        gPlayers.init(function(err) {
            if (err) {
                ERROR("can't load CloudUser");
                process.exit(-1);
            }
            INFO('CloudUser loaded');

            loadCloud(startCloud);
        });
    });
})();

function startCloud() {
    server.startWebServer('cloud', config.CloudPort, config.CloudHost , function(query, res, resp){
        var logicHandler = null;
        var module = logic[query.mod];

        if( module ) {
            logicHandler = module[query.act];
        }

        if( !logicHandler ) {
            resp.code = 1;
            resp.desc = 'act ' + query.act + ' not support in mod ' + query.mod;
            onReqHandled(res, resp);
            return;
        }
        
        if (query.std) {
            var user = query.args.user || {};
            user._id = query.uid;

            gPlayers.load(user, function(player) {
                delete query.args.user;

                if (!player) {
                    resp.code = 1; 
                    resp.desc = 'cloud player invalid';
                    onReqHandled(res, resp);
                    return;
                }

                logicHandler(player, query, resp, function(){
                    onReqHandled(res, resp);
                });
            });
        } else {
            logicHandler(query, res, resp);
        }
    }, function(callback) {
        // 退出处理
        gServerMine.saveUser();

        var forceSave = true;
        var loader = new common.Loader(callback);
        loader.addLoad('empty');    // 防止没有需要Load的时候不结束

        // 强制保存云购
        loader.addLoad('cloud_shop');
        gCloudShop.save(function(succ){
            LOG('save cloud_shop success');
            loader.onLoad('cloud_shop');
        });

        // 强制保存决战天下
        loader.addLoad('battle_world');
        var forceSave = true;
        gBattleWorld.save(forceSave, function(succ){
            LOG('save battle_world success');
            loader.onLoad('battle_world');
        });

        // 强制保存金矿
        loader.addLoad('server_mine');
        var forceSave = true;
        gServerMine.save(forceSave, function(succ){
            LOG('save server_mine success');
            loader.onLoad('server_mine');
        });

        // 强制保存幸运号码
        loader.addLoad('lucky_number');
        gLuckyNumber.save(function(succ){
            LOG('save lucky_number success');
            loader.onLoad('lucky_number');
        });

        // 强制保存大乐透
        loader.addLoad('lottery');
        gLottery.save(function(succ){
            LOG('save lottery success');
            loader.onLoad('lottery'); 
        });
        
        //强制保存玩家数据
        loader.addLoad('cloud_user');
        gPlayers.save(forceSave, function(err) {
            LOG('save cloud_user success');
            loader.onLoad('cloud_user');
        });
        
        //强制保存王者战场数据
        loader.addLoad('champsbattle');
        gChampsBattle.save(forceSave, function(err) {
            LOG('save champsbattle success');
            loader.onLoad('champsbattle');
        });

        loader.onLoad('empty');
    });

    //timer_30minutes();
    timer_5minutes();
    timer_2minutes();
    timer_1sec();
}

function loadCloud(callback) {
    var loader = new common.Loader(callback);    

    // 加载云购
    loader.addLoad('cloud_shop');
    var CloudShop = require('./cloud/cloudshop.js').CloudShop;
    global.gCloudShop = new CloudShop();
    gCloudShop.init(function(succ){
        if( !succ ) {
            ERROR("can't load CloudShop");
            process.exit(-1);
        }
        INFO('CloudShop loaded');
        loader.onLoad('cloud_shop');
    });

    // 加载决战天下
    loader.addLoad('battle_world');
    var BattleWorld = require('./cloud/battleworld.js').BattleWorld;
    global.gBattleWorld= new BattleWorld();
    gBattleWorld.init(function(succ){
        if( !succ ) {
            ERROR("can't load BattleWorld");
            process.exit(-1);
        }
        INFO('BattleWorld loaded');
        loader.onLoad('battle_world');
    });

    // 加载Replay
    loader.addLoad('replay');
    var Replay = require('./world/replay.js').Replay;
    global.gReplay = new Replay();
    gReplay.init(function(succ){
        if( !succ ) {
            ERROR("can't load replay");
            process.exit(-1);
        }
        INFO('replay loaded');
        loader.onLoad('replay');
    });

    // 加载战术大赛
    loader.addLoad('troop_match');
    var TroopMatch = require('./cloud/troopmatch.js').TroopMatch;
    global.gTroopMatch = new TroopMatch();
    gTroopMatch.init(function(succ){
        if( !succ ) {
            ERROR("can't load TroopMatch");
            process.exit(-1);
        }
        INFO('TroopMatch loaded');
        loader.onLoad('troop_match');
    });

    // 加载活动
    loader.addLoad('activity');
    var Activity = require('./cloud/activity.js').Activity;
    global.gActivity = new Activity();
    gActivity.init(function(succ){
        if( !succ ) {
            ERROR("can't load activity");
            process.exit(-1);
        }
        INFO('activity loaded');
        loader.onLoad('activity');
    });

    // 加载金矿
    loader.addLoad('server_mine');
    var ServerMine = require('./cloud/servermine.js').ServerMine;
    global.gServerMine = new ServerMine();
    gServerMine.init(function(succ){
        if( !succ ) {
            ERROR("can't load server_mine");
            process.exit(-1);
        }
        INFO('server_mine loaded');
        loader.onLoad('server_mine');
    });

    // 加载幸运号码
    loader.addLoad('lucky_number');
    var LuckyNumber = require('./cloud/activity.js').LuckyNumber;
    global.gLuckyNumber = new LuckyNumber();
    gLuckyNumber.init(function(succ){
        if( !succ ) {
            ERROR("can't load lucky_number");
            process.exit(-1);
        }
        INFO('lucky_number loaded');
        loader.onLoad('lucky_number');
    });

    // 加载大乐透
    loader.addLoad('lottery');
    var Lottery = require('./cloud/lottery.js').Lottery;
    global.gLottery = new Lottery();
    gLottery.init(function(succ){
        if( !succ ){
            ERROR("can't load lottery"); 
            process.exit(-1);
        } 
        INFO('lottery loaded');
        loader.onLoad('lottery');
    });

    // 加载横扫九州
    loader.addLoad('cloudSmashland');
    var CloudSmashLand = require('./cloud/smashland.js').CloudSmashLand;
    global.gCloudSmashLand = new CloudSmashLand();
    gCloudSmashLand.init(function(succ) {
        if( !succ ){
            ERROR("can't load cloudSmashland"); 
            process.exit(-1);
        } 
        INFO('cloudSmashland loaded');
        loader.onLoad('cloudSmashland');
    });
    
    //加载王者战场
    loader.addLoad('champsbattle');
    var ChampsBattle = require('./cloud/champsbattle.js').ChampsBattle;
    global.gChampsBattle = new ChampsBattle();
    gChampsBattle.init(function(err) {
        if (err) {
            ERROR("can't load champsbattle");
            process.exit(-1);
        }

        INFO('champsbattle loaded');
        loader.onLoad('champsbattle');
    });
}

function timer_30minutes() {
    setInterval(function(){
        gCloudSmashLand.rank();
    }, 30 * 60 * 1000);
}

function timer_5minutes() {
    setInterval(function(){
        gCloudShop.save();
        gPlayers.save();
        gChampsBattle.save();
    }, 5 * 60 * 1000);
}

function timer_2minutes() {
    setInterval(function(){
        gCloudSmashLand.rank();
    }, 2 * 60 * 1000);
}

function timer_1sec() {
    setInterval(function(){
        try {
            gBattleWorld.tick();
            gChampsBattle.tick();
        } catch (e) {
            ERROR(e.stack);
        }
    }, 1000);
}
